package org.example.old.listener;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.util.ListUtils;
import lombok.extern.slf4j.Slf4j;
import org.example.old.dto.SysDto;
import org.example.old.service.SysService;

import java.util.List;
import java.util.Map;

@Slf4j
public class NoModelDataListener extends AnalysisEventListener<SysDto> {
    /**
     * 每隔3000条存储数据库，清理list，方便内存回收
     */
    private static final int BATCH_COUNT = 3000;
    private List<SysDto> list = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    SysService sysService;

    public NoModelDataListener(SysService sysService) {
        this.sysService = sysService;
    }

    @Override
    public void invoke(SysDto sysDto, AnalysisContext analysisContext) {
        log.info("解析到一条数据：{}",sysDto.toString());
        list.add(sysDto);
        if(list.size() >= BATCH_COUNT){
            saveData();
            list = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("解析完成");
    }



    /**
     * 批量保存数据
     */
    public  void saveData(){
        log.info("{}条数据，开始存储",list.size());
        sysService.addUserList(list);
        log.info("存储成功");
    }

}
